package com.chy.blog_server.modular.system.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chy.blog_server.core.util.RandomValidateCodeUtil;
import com.chy.blog_server.core.util.UserUtil;
import com.chy.blog_server.modular.system.entity.SysUser;
import com.chy.blog_server.modular.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：登录控制器
 * 作者：chenhuiyan
 * 时间：2020-02-12
 */
@Controller
@RequestMapping(value = "/sys/login")
public class LoginContoller {

    /**
     * 前缀
     */
    private static String PREFIX = "system/login/";

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(LoginContoller.class);

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 跳转登录页面
     * @return
     */
    @CacheEvict(value = "sysMenuTreeVO")
    @RequestMapping(value = "")
    public String loginIndex(){
        return PREFIX + "login";
    }

    /**
     * 登录验证
     * @param userName
     * @param password
     * @param captcha
     * @return
     */
    @RequestMapping(value = "/loginVerify")
    @ResponseBody
    public Map<String, Object> loginVerify(String userName, String password, String captcha, HttpSession session, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try{
            //验证码校验
            boolean verify = checkVerify(captcha, session);
            if(!verify){
                res.put("state", "500");
                res.put("message", "验证码错误");
                return res;
            }

            //根据用户名查找用户
            SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("user_name", userName));

            if(ObjectUtil.isNotNull(sysUser)){
                //帐号状态验证
                if(0 == sysUser.getStatus()){
                    //密码验证(长度大于20视为已是MD5加密的密码)
                    if(password.length() > 25){
                        if(password.equals(sysUser.getPassword())){

                            //保存登录用户到session
                            UserUtil.putUserIntoSession(request, sysUser);

                            res.put("state", "200");
                            res.put("message", "登录成功");
                            return res;
                        }else{
                            res.put("state", "500");
                            res.put("message", "帐号或密码错误");
                            return res;
                        }
                    }else{
                        String passwordToMd5 = SecureUtil.md5(password);
                        if(sysUser.getPassword().equals(passwordToMd5)){

                            //保存登录用户到session
                            UserUtil.putUserIntoSession(request, sysUser);

                            res.put("state", "200");
                            res.put("message", "登录成功");
                            return res;
                        }else{
                            res.put("state", "500");
                            res.put("message", "帐号或密码错误");
                            return res;
                        }
                    }

                }else if(1 == sysUser.getStatus()){
                    res.put("state", "500");
                    res.put("message", "该帐号已被冻结");
                    return res;
                }else{
                    res.put("state", "500");
                    res.put("message", "该帐号已被封停");
                    return res;
                }
            }else{
                res.put("state", "500");
                res.put("message", "帐号或密码错误");
                return res;
            }

        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，登录失败！");
        }
        return res;
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping(value = "/logout")
    @ResponseBody
    public Map<String, Object> logout(HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        res.put("state", "500");
        res.put("message", "退出登录失败");
        try {
            boolean flag = UserUtil.removeUserIntoSession(request);
            if(flag){
                res.put("state", "200");
                res.put("message", "退出登录成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            logger.error("获取验证码失败>>>>   ", e);
        }
    }

    /**
     * 校验验证码
     */
    public boolean checkVerify(String verifyInput, HttpSession session) {
        try{
            //从session中获取随机数
            String inputStr = verifyInput;
            String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
            if (random == null) {
                return false;
            }
            if (random.equalsIgnoreCase(inputStr)) {
                return true;
            } else {
                return false;
            }
        }catch (Exception e){
            logger.error("验证码校验失败", e);
            return false;
        }
    }

}
